
import $com from '@/utils/custom-plugin/custom.js'
import $constant from '@/utils/open/constant.js';
jq(function () {
  console.log('$constant.urlParams 参数:', $constant.urlParams)

  var PageTitledom = parent.document.getElementsByTagName('title');
  // debugger
  PageTitledom[0].text = PageTitledom[0].text + '-' + $constant.sysName;

  createTestBoxFn() //  test 调试使用
  // 由于mui已阉割a标签默认事件，这里重新定义上
  mui(document).on('tap', 'a:not(tellphone)', function (e) {
    // console.log(e)
    // debugger
    // return
    // console.log(this)
    let href = this.getAttribute('href')
    if (!href) {
      this.click()
      return
    }
    if (href.indexOf('javascript:') === 0) {
      var a = document.createElement('a')
      a = this.cloneNode(true)
      // debugger
      a.click()
    } else {
      if (href.indexOf('./') === 0) {
        href.replace('./', '')
      }
      jumpRouter(href) // 页面跳转方法，来源 common.js
    }
  });

  // 点击按钮，让获取焦点的表单元素失去焦点，以便隐藏手机端虚拟键盘
  mui('body').on('tap', '.btn-box .btn', function (e) {
    // console.log('document.activeElement：', document.activeElement);
    const actEle = document.activeElement;
    if (actEle) {
      actEle.blur();
    }
  })

})

/**
 * 搜索功能初始化
 * @param {String} domId
 * @param {Object} config
 *  initSearchValFn 返回搜索关键字
 * @param {Function} fn 回调函数
 */
function initSearchFn(domId, config, fn) {
  const searchBoxDom = document.querySelector(domId);
  if (searchBoxDom && fn) {
    // dom元素准备
    searchBoxDom.classList.add('search-box', 'clearfix');

    const inputBox = document.createElement('div');
    inputBox.classList.add('fl', 'input-box');

    const searchIcon = document.createElement('i');
    searchIcon.classList.add('iconfont', 'icon-search', 'search-icon');

    const cleanIcon = document.createElement('i');
    cleanIcon.classList.add('iconfont', 'icon-close', 'clean-icon');

    const inputDom = document.createElement('input');
    inputDom.classList.add('search-input');
    inputDom.type = 'text';
    inputDom.setAttribute('placeholder', config.placeholder || '请输入搜索关键字')

    inputBox.appendChild(searchIcon);
    inputBox.appendChild(inputDom);
    inputBox.appendChild(cleanIcon);

    const searchBtn = document.createElement('div');
    searchBtn.classList.add('fr', 'search-btn');
    searchBtn.innerText = '搜索';

    searchBoxDom.appendChild(inputBox);
    searchBoxDom.appendChild(searchBtn);

    // 添加了防抖函数
    inputDom.addEventListener('input', $com.debounce(function () {
      if ($com.isNull(this.value)) {
        cleanIcon.style.display = 'none';
      } else {
        cleanIcon.style.display = 'inline-block';
      }
      if (config.initSearchValFn) {
        config.initSearchValFn(inputDom)
      }
      fn()
    }));
    // 清空
    cleanIcon.addEventListener('tap', function (e) {
      inputDom.value = '';
      cleanIcon.style.display = 'none';
      if (config.initSearchValFn) {
        config.initSearchValFn(inputDom)
      }
      fn()
    });
    // 搜索按钮
    searchBtn.addEventListener('tap', function (e) {
      if (!$com.isNull(inputDom.value)) {
        fn()
      } else {
        $mui.toast(config.placeholder || '请输入搜索关键字')
      }
    });
  }
}

/**
 * 修改页面标题
 */
function changePageTitle(num, roomState) {
  // debugger
  if (!$com.isNull(roomState)) { // 根据房产地址 判断地产和物业
    // isProperty: 1.地产 2.物业
    if (Number(roomState) >= 4) {
      num = 2;
    } else {
      num = 1
    }
  }
  // console.log($constant.isProperty)
  $constant.isProperty = num;
  $com.setSession('isProperty', num);
  $constant.sysName = '地产-聚星源';
  // debugger
  if (num === 2) {
    $constant.sysName = '物业-聚星源';
  }

  // debugger
  var headTitle = PageTitledom[0].text;
  headTitle = headTitle.split('-');
  PageTitledom[0].text = headTitle[0] + '-' + $constant.sysName;
}

/**
 * 页面跳转
 * @param {String} url 跳转路径
 * @param {Object} data 页面传参
 * @param {Boolean} isReplace 是否 替换路由
 * @param {String} sysbol 目录级别字符 ../
 */
function jumpRouter(url, data, isReplace, sysbol) {
  // debugger
  let href = ''
  if (url.indexOf('../') > -2 || url.indexOf('./') > -1) {
    href = url
  } else {
    sysbol = sysbol || '../../'
    href = sysbol + 'estate/html/' + url
    // 1.地产 2.物业
    if ($constant.isProperty === 2) {
      href = sysbol + 'property/html/' + url
    }
  }

  let query = null
  if (!$com.isNull(data)) {
    query = $com.obj2Str(data)

    if (!$com.isNull(query)) {
      href += query
    }
  }

  if (isReplace) {
    parent.window.location.replace(href)
  } else {
    parent.window.location.href = href
  }
}

/**
 * 跳转详情
 * @param {Array} arr 列表数组数据
 * @param {String|Number}} id 
 */
function jumpToDetail(arr, id, key) {
  // alert('跳转详情')
  for (let obj of arr) {
    if (id === obj[key]) {
      // 详情需要的数据
      let queryData = {
        operationId: '',
        id: '', // 记录id
      }
      queryData = $com.copyObjComVal(queryData, obj); // 复制对象公共属性
      jumpRouter('../../public/html/work-order-detial.html', queryData); // 页面跳转方法，来源 common.js
      break;
    }
  }
}
/**
 * test 调试使用
 */
function createTestBoxFn() {
  let testBtn = document.querySelector('#DialogTextBtn')
  if (location.href.indexOf('login.html') <= -1 && !testBtn) {
    let testBtn = document.createElement('div')
    testBtn.id = 'DialogTextBtn'
    testBtn.className = 'dialog-test-box'
    testBtn.innerHTML = '测试'
    document.body.appendChild(testBtn)
    mui(document).on('tap', '#DialogTextBtn', function (e) {
      layer.open({
        type: 2,
        title: '测试',
        shadeClose: true,
        shade: 0.6,
        btn: ['关闭'],
        area: ['100%', '100%'],
        content: '../../public/html/login.html' //iframe的url
      })
    })

    // new $DRAGANDDROP('#DialogTextBtn');
  }
}

/**
 * 日期组件 绑定表单组件
 * @param {Object} eleName 父级dom元素 class id
 * @param {String} childEleName 相对父级的子级元素名字 class id
 * 注意：该方法需要引进mui插件
 *  <link rel="stylesheet" type="text/css"href="../../public/css/plugin/mui.picker.min.css"></link>
    <script src="../../public/js/mui.picker.min.js"></script>
 */
function bindDatePicker(eleName, childEleName) {
  childEleName = childEleName || 'input.input-cls'
  // 日期组件
  mui(eleName)[0].addEventListener(
    'tap',
    function () {
      var _self = this
      if (_self.picker) {
        _self.picker.show(function (rs) {
          // result.innerText = '选择结果: ' + rs.text;
          _self.picker.dispose()
          _self.picker = null
        })
      } else {
        var optionsJson = this.getAttribute('data-options') || '{}'
        var options = JSON.parse(optionsJson)
        var id = this.getAttribute('id')
        /*
         * 首次显示时实例化组件
         * 示例为了简洁，将 options 放在了按钮的 dom 上
         * 也可以直接通过代码声明 optinos 用于实例化 DtPicker
         */
        _self.picker = new mui.DtPicker(options)
        _self.picker.show(function (rs) {
          /*
           * rs.value 拼合后的 value
           * rs.text 拼合后的 text
           * rs.y 年，可以通过 rs.y.vaue 和 rs.y.text 获取值和文本
           * rs.m 月，用法同年
           * rs.d 日，用法同年
           * rs.h 时，用法同年
           * rs.i 分（minutes 的第二个字母），用法同年
           */
          const childDom = jq(_self).find(childEleName)[0]
          childDom.value = rs.text
          childDom.dataset.value = rs.text
          // jq(_self).find(childEleName)[0].value = rs.text;
          /*
           * 返回 false 可以阻止选择框的关闭
           * return false;
           */
          /*
           * 释放组件资源，释放后将将不能再操作组件
           * 通常情况下，不需要示放组件，new DtPicker(options) 后，可以一直使用。
           * 当前示例，因为内容较多，如不进行资原释放，在某些设备上会较慢。
           * 所以每次用完便立即调用 dispose 进行释放，下次用时再创建新实例。
           */
          _self.picker.dispose()
          _self.picker = null
        })
      }
    },
    false
  )
}

/**
 * 普通下拉选项 绑定表单组件
 * @param {Array} list picker的数组对象 ，对象的key只能为value和text
 * @param {Object} eleName 父级dom元素 class id
 * @param {Object} config 扩展参数 
 *  childEleName 相对父级的子级元素名字 class id
 *  initFinsh 初始化完毕回调
 *  fn 选中回调
 *  defaultSelectIndex 默认选中第几项
 * 
 * 注意：该方法需要引进mui-picker插件
 *  <link rel="stylesheet" type="text/css"href="../../public/css/plugin/mui.picker.min.css"></link>
    <script src="../../public/js/mui.picker.min.js"></script>
 */
function bindSelectPicker(list, eleName, config) {
  if (!eleName) {
    console.error('bindSelectPicker-绑定失败')
    $mui.toast('bindSelectPicker-绑定失败')
    return
  }
  // debugger
  const oPickerDom = document.querySelector(eleName)
  if (oPickerDom.PICKER) {
    oPickerDom.PICKER.setData(list)
    return
  }

  config = config || {}
  let childEleName = config.childEleName || 'input.input-cls'

  // picker 普通示例
  oPickerDom.PICKER = new mui.PopPicker()

  oPickerDom.PICKER.setData(list)

  // 选中默认项
  if (!isNaN(config.defaultSelectIndex)) {
    oPickerDom.PICKER.pickers[0].setSelectedIndex(config.defaultSelectIndex) // 设置默认选中值
  }

  // 初始化完毕回调
  if (config.initFinsh && !isNaN(config.defaultSelectIndex)) {
    handleCallBack(list[config.defaultSelectIndex], oPickerDom)
    config.initFinsh(oPickerDom.PICKER, config)
  }

  // oPickerDom.PICKER.pickers[0].setSelectedIndex(1); // 一级 设置默认选中值
  oPickerDom.addEventListener('tap', function () {
    oPickerDom.PICKER.show(function (items) {
      // debugger
      handleCallBack(items[0], oPickerDom)
    })
  }, false)

  // 操作回调函数
  function handleCallBack(obj, oPickerDom) {
    if ($com.isNull(obj)) return
    // let t1 = jq(eleName);
    // let t2 = jq(eleName).find(childEleName)
    // console.log('t1:', t1)
    // console.log('t2:', t2)
    const childDom = jq(eleName).find(childEleName)

    for (let i = 0; i < childDom.length; i++) {
      const oDom = childDom[i]
      const key = oDom.name

      let val = obj[key]
      // debugger
      if ($com.isNull(val)) {
        val = obj.value
      }

      // 表单项的value是用来显示label的，data-value才是用来传参，自动获取表单，获取的是 data-value
      oDom.dataset.value = val // 自动获取表单值，以 data-value 为 value
      oDom.value = obj.text // value 为显示内容
    }

    // childDom.value = obj.text
    // childDom.dataset.value = obj.value
    //返回 false 可以阻止选择框的关闭
    //return false;
    if (config.fn) {
      config.fn(obj, oPickerDom)
    }
  }
}

/**
 * 数字输入框封装
 * @param {String} domId
 * @param {Object} config
 * @param {Function} fn
 * new $InitNumberBox()
 */
const $InitNumberBox = function (domId, config) {
  config = config || {}
  const conf = {
    min: 0,
    max: 10000,
    initNum: 0,
    inputName: ''
  }
  for (let k in conf) {
    if (k && config.hasOwnProperty(k)) {
      conf[k] = config[k]
    }
  }
  // debugger
  this.min = conf.min
  this.max = conf.max
  this.number = conf.initNum
  this.inputName = conf.inputName
  this.originNum = conf.initNum // 用来对比前后差，以判断是加还是减
  // debugger

  this.oDom = document.querySelector(domId)
  // this.oReduce = this.oDom.querySelector('.reduce');
  // this.oPlus = this.oDom.querySelector('.plus');
  // this.oInput = this.oDom.querySelector('.num-input');
  this.fn = config.fn
  this.createDom()
  this.init()
}
$InitNumberBox.prototype = {
  init() {
    const _this = this
    this.oReduce.addEventListener('click', () => {
      _this.reduce()
    })
    this.oPlus.addEventListener('click', () => {
      _this.plus()
    })
    this.oInput.addEventListener('change', () => {
      _this.change()
    })
  },
  createDom() {
    this.oDom.classList.add('number-box', 'flex')

    this.oReduce = document.createElement('span')
    this.oReduce.classList.add('reduce')
    this.oReduce.innerHTML = '-'
    // debugger
    if (this.number > this.min) {
      this.oReduce.classList.add('active')
    }

    this.oInput = document.createElement('input')
    this.oInput.classList.add('num-input')
    this.oInput.type = 'text'
    this.oInput.name = this.inputName
    this.oInput.value = this.number

    this.oPlus = document.createElement('span')
    this.oPlus.classList.add('plus')
    this.oPlus.innerHTML = '+'
    if (this.number < this.max) {
      this.oPlus.classList.add('active')
    }

    this.oDom.appendChild(this.oReduce)
    this.oDom.appendChild(this.oInput)
    this.oDom.appendChild(this.oPlus)
  },
  /**
   * 减
   */
  reduce() {
    // debugger
    if (this.number > this.min) {
      this.number--
      this.oInput.value = this.number
    }
    this.change()
  },
  /**
   * 加
   */
  plus() {
    // debugger
    if (this.number < this.max) {
      this.number++
      this.oInput.value = this.number
    }
    this.change()
  },
  /**
   * 值变动触发
   */
  change() {
    // console.log('change')

    let oprationTxt = 'plus'
    if (this.originNum <= this.number) {
      oprationTxt = 'reduce'
    }
    // 减号 的激活状态判断
    if (this.number <= this.min) {
      this.oReduce.classList.remove('active')
    } else {
      this.oReduce.classList.add('active')
    }

    // 加号 的激活状态判断
    if (this.number >= this.max) {
      this.oPlus.classList.remove('active')
    } else {
      this.oPlus.classList.add('active')
    }

    // console.log(oprationTxt, this.number)

    this.originNum = this.number
    if (this.fn) {
      this.fn({
        oprationTxt: this.oprationTxt,
        number: this.number
      })
    }
  }
}

/**
 * switchTab 初始化
 * 包含 接口请求，事件等
 * @param {String} domId
 * @param {Object} config
 *  tabList array tab项
 *  curSelectTab Number|String 当前雪中的tab索引
 *  clickEvents Function
 */
const $InitSwitchTab = function (domId, config) {
  config = config || {}
  this.dom = document.querySelector(domId)
  if (!this.dom) return
  this.dom.classList.add('line-tab')
  const _this = this
  this.conf = {
    tabList: [],
    // paramsObj: null,
    curSelectTab: 0, // 默认选中
    clickEvents: null,
    callBackFn: null,
    itemW: 100 // 每个tab的宽度
  }

  for (let key in config) {
    // debugger
    if (key && this.conf.hasOwnProperty(key)) {
      this.conf[key] = config[key]
    }
  }

  // 整个逻辑都是围绕 tabList 展开
  if (this.conf.tabList.length > 0) {
    this.init()
    this.initEvent()
    _this.updateDom() // 请求的数据&更新dom
  }
}
$InitSwitchTab.prototype = {
  init() {
    const tabsArr = this.conf.tabList
    const tabLen = tabsArr.length

    const tabWrapDom = document.createElement('div')
    tabWrapDom.classList.add('tab-wrap')

    if (tabLen > 3) {
      tabWrapDom.style.width = tabLen * this.conf.itemW + 'px'
    } else {
      tabWrapDom.classList.add('flex')
      tabWrapDom.style.width = '100%'
    }

    tabsArr.forEach((obj, index) => {
      obj.tabItem = document.createElement('div')
      obj.tabItem.classList.add('tab-item')
      if (this.conf.curSelectTab === index) {
        obj.tabItem.classList.add('active')
      }
      obj.tabItem.dataset.index = index

      const textDom = document.createElement('span')
      textDom.classList.add('tab-text')
      textDom.innerText = obj.text
      textDom.dataset.index = index

      obj.numDom = document.createElement('span')
      obj.numDom.classList.add('tab-total')
      obj.numDom.dataset.index = index
      obj.numDom.innerText = '(0)'

      obj.tabItem.appendChild(textDom)
      obj.tabItem.appendChild(obj.numDom)

      tabWrapDom.appendChild(obj.tabItem)
    })

    this.dom.appendChild(tabWrapDom)
  },
  /**
   * 事件初始化
   */
  initEvent() {
    const _this = this
    // 图片上传组件 点击事件 绑定
    this.dom.addEventListener('tap', function (e) {
      const target = e.target
      // console.log('target', target)
      // console.log('classList', target.classList)
      if (!target) return
      // debugger
      // 删除图片
      if (
        target.classList.contains('tab-item') ||
        target.classList.contains('tab-text') ||
        target.classList.contains('tab-total')
      ) {
        const index = target.dataset.index
        _this.switchTab(index)
      }
    })
  },
  /**
   * 当前点击dom的索引
   * @param {Number|String} index
   */
  switchTab(index) {
    const _this = this
    // debugger
    index = Number(index)
    if (this.conf.curSelectTab === index) {
      return
    }
    this.conf.tabList.forEach(obj => {
      const dom = obj.tabItem
      const i = Number(dom.dataset.index)
      if (this.conf.curSelectTab === i) {
        dom.classList.remove('active')
      }
    })
    const curTabItem = this.conf.tabList[index]
    curTabItem.tabItem.classList.add('active')
    this.conf.curSelectTab = index

    // 委托事件回调
    if (_this.conf.callBackFn) {
      _this.conf.callBackFn(curTabItem)
    }
  },
  /**
   * 请求的数据&更新dom
   * @param {Object} data
   */
  updateDom() {
    if (this.conf.clickEvents) {
      this.conf.clickEvents().then(res => {
        const data = res.data
        this.conf.tabList.forEach(obj => {
          const val = '(' + data[obj.fileName] + ')';
          // debugger
          obj.numDom.innerHTML = val;
        })
      })
    }

  }
}
